<?php
namespace plugin\ky_shouyin\app\service;

use support\Db;

class MemberCardService
{
    /**
     * 生成会员卡
     */
    public function generate($prefix = 'VIP', $count = 500)
    {
        try {
            Db::beginTransaction();
            
            $cards = [];
            $now = date('Y-m-d H:i:s');
            
            // 获取最后一个卡号
            $lastCard = Db::table('ky_member_card')
                ->where('card_no', 'like', $prefix.'%')
                ->orderBy('card_no', 'desc')
                ->first();
                
            $lastNum = 0;
            if ($lastCard) {
                $lastNum = (int)substr($lastCard->card_no, strlen($prefix));
            }
            
            // 生成新卡号
            for ($i = 1; $i <= $count; $i++) {
                $num = $lastNum + $i;
                $cardNo = $prefix . str_pad($num, 6, '0', STR_PAD_LEFT);
                
                // 计算校验位（可以根据需要实现具体的校验算法）
                $checkDigit = $this->calculateCheckDigit($cardNo);
                
                $cards[] = [
                    'card_no' => $cardNo,
                    'prefix' => $prefix,
                    'number' => $num,
                    'check_digit' => $checkDigit,
                    'status' => 0, // 0表示未使用
                    'created_at' => $now,
                    'updated_at' => $now
                ];
            }
            
            // 批量插入
            foreach(array_chunk($cards, 100) as $chunk) {
                Db::table('ky_member_card')->insert($chunk);
            }
            
            Db::commit();
            return ['code' => 0, 'msg' => '生成成功'];
        } catch (\Exception $e) {
            Db::rollBack();
            return ['code' => 1, 'msg' => '生成失败：' . $e->getMessage()];
        }
    }

    /**
     * 计算校验位
     */
    private function calculateCheckDigit($cardNo)
    {
        // 简单的校验算法：将所有数字相加，取个位数
        $sum = 0;
        for ($i = 0; $i < strlen($cardNo); $i++) {
            if (is_numeric($cardNo[$i])) {
                $sum += intval($cardNo[$i]);
            }
        }
        return $sum % 10;
    }
} 